package com.xyxy.platform.website.service.web.controller;

import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.xyxy.platform.modules.core.file.SystemFileService;
import com.xyxy.platform.modules.core.solr.SolrClientService;
import com.xyxy.platform.modules.core.solr.SolrSearchParams;
import com.xyxy.platform.modules.core.utils.Collections3;
import com.xyxy.platform.modules.core.utils.ResponseUtils;
import com.xyxy.platform.modules.core.web.bind.annotation.CurrentUser;
import com.xyxy.platform.modules.core.web.controller.BaseController;
import com.xyxy.platform.modules.core.web.response.ResponseMessage;
import com.xyxy.platform.modules.entity.content.Article;
import com.xyxy.platform.modules.entity.image.ImageItem;
import com.xyxy.platform.modules.entity.image.ImageTypes;
import com.xyxy.platform.modules.entity.member.Member;
import com.xyxy.platform.modules.entity.member.MemberSpecificTag;
import com.xyxy.platform.modules.entity.member.SpecificTag;
import com.xyxy.platform.modules.entity.trade.Category;
import com.xyxy.platform.modules.entity.trade.Goods;
import com.xyxy.platform.modules.entity.trade.GoodsServerTime;
import com.xyxy.platform.modules.entity.trade.ServerTags;
import com.xyxy.platform.modules.service.content.ArticleService;
import com.xyxy.platform.modules.service.image.ImageItemService;
import com.xyxy.platform.modules.service.member.MemberService;
import com.xyxy.platform.modules.service.member.MemberSpecificTagService;
import com.xyxy.platform.modules.service.member.SpecificTagService;
import com.xyxy.platform.modules.service.sns.CollectionService;
import com.xyxy.platform.modules.service.trade.CategoryService;
import com.xyxy.platform.modules.service.trade.GoodsServerTimeService;
import com.xyxy.platform.modules.service.trade.GoodsService;
import com.xyxy.platform.modules.service.trade.ServerTagService;
import com.xyxy.platform.website.common.vo.CurrentLoginUser;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.validation.Validator;
import java.util.List;
import java.util.Map;

/**
 * 简介: 服务广场
 *
 * @author Caizhenegda
 * @version 1.0
 * @Date 2016-01-06 15:00
 */
@Controller
@RequestMapping(value = "/service")
public class ServiceController extends BaseController {

    @Autowired
    private Validator validator; //表单验证

    @Autowired
    private CategoryService categoryService; //服务分类

    @Autowired
    private GoodsService goodsService; //服务信息

    @Autowired
    private ImageItemService imageItemService; //图片

    @Autowired
    private SystemFileService systemFileService; //文件处理

    @Autowired
    private ServerTagService serverTagService; //服务标签

    @Autowired
    private GoodsServerTimeService serverTimeService; //服务时间段

    @Autowired
    private CollectionService collectionService; //会员收藏服务

    @Autowired
    private ArticleService articleService; // 文章服务, 如 服务详情

    @Autowired
    private MemberService memberService; //会员

    @Autowired
    private MemberSpecificTagService memberSpecificTagService; // 用户便签关联

    @Autowired
    private SpecificTagService specificTagService; // 个性标签

    @Autowired
    private SolrClientService solrClientService;


    /**
     * 根据父级分类ID 查询分类信息
     *
     * @param categoryParentId 父级分类ID
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "category/list", method = RequestMethod.GET)
    public ResponseMessage<?> categoryList(@RequestParam(defaultValue = "0") Long categoryParentId) {
        List<Category> categoryList = categoryService.findByParentId(categoryParentId);
        return ResponseUtils.jsonSuccess(categoryList, "查询分类列表成功!");
    }

    /**
     * 首页
     *
     * @param currentLoginUser
     * @param model
     * @return
     */
    @RequestMapping(value = "index", method = RequestMethod.GET)
    public String indexView(@CurrentUser CurrentLoginUser currentLoginUser, Model model) {
        model.addAttribute("user", currentLoginUser);
        return "service/index";
    }

    /**
     * 某分类页面
     *
     * @param categoryId
     * @param model
     * @return
     */
    @RequestMapping(value = "category/{categoryId}", method = RequestMethod.GET)
    public String categoryView(@PathVariable("categoryId") Long categoryId, Model model) {
        Category category = categoryService.findById(categoryId);
        model.addAttribute("parentCategory", category);
        return "service/index_children";
    }

    /**
     * 分页查询 服务列表信息
     *
     * @param pageNum    第几页
     * @param pageSize   一页多少天
     * @param searchType 0:推荐, 1最新
     * @param categoryId 服务 分类ID
     * @param serverType 服务类型: 想着咨询, 天使投资
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "goods/list", method = RequestMethod.GET)
    public ResponseMessage<?> searchGoods(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "15") Integer pageSize,
            @RequestParam(defaultValue = "0") Integer searchType,
            Long categoryId,
            Integer serverType) {

        SolrSearchParams solrSearchParams = new SolrSearchParams();
        solrSearchParams.setPageNum(pageNum + 1);
        solrSearchParams.setPageSize(pageSize);
        StringBuffer q = new StringBuffer("*:* ");
        if (null != categoryId) {
            q.append("AND categories:").append(categoryId).append(" ");
        }
        switch (searchType) {
            case 0: //推荐
                q.append("isBest:true").append(" ");
                break;
            case 1: //最新
                solrSearchParams.setSort("createTime desc");
                break;
            default:
        }
        if (null != serverType) {
            q.append("AND serverType:").append(serverType);
        }
        solrSearchParams.setQ(q.toString());

        QueryResponse queryResponse = solrClientService.query("core0", solrSearchParams);

        PageInfo<SolrDocument> pageInfo = new PageInfo<>();
        if (null != queryResponse) {
            SolrDocumentList docs = queryResponse.getResults();
            for (SolrDocument solrDocument : docs) {
                Object coverImage = solrDocument.get("coverImage");
                if (null != coverImage)
                    solrDocument.setField("coverImage", systemFileService.getFileUrlByUri(coverImage.toString()));
                Object memberHeadImage = solrDocument.get("memberHeadImage");
                if (null != coverImage)
                    solrDocument.setField("memberHeadImage", systemFileService.getFileUrlByUri(memberHeadImage.toString()));
            }
            pageInfo.setTotal(docs.getNumFound());
            pageInfo.setList(docs);
        }


        return ResponseUtils.jsonSuccess(pageInfo, "分页查询服务信息成功!");
    }

    /**
     * 详情页
     *
     * @param id 服务ID
     * @return
     */
    @RequestMapping(value = "detail/{id}", method = RequestMethod.GET)
    public String detail(@PathVariable("id") Long id, @CurrentUser CurrentLoginUser user, Model model) {
        Goods goods = goodsService.selectByPrimaryId(id);
        //查询服务部存在
        if (null == goods) {
            return super.page404;
        }
        //非开启状态服务 非本人不可访问
        if (goods.getIsSale() == 0 && (null == user || !user.getId().equals(goods.getMemberId()))) {
            return super.page404;
        }
        model.addAttribute("goodsId", id);
        model.addAttribute("memberId", goods.getMemberId());
        return "service/detail";
    }

    /**
     * 服务详情页-主剃信息
     *
     * @param goodsId 服务ID
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "detail/data/main", method = RequestMethod.GET)
    public ResponseMessage<?> detailDataMain(@RequestParam Long goodsId, @CurrentUser CurrentLoginUser user) {
        // 基本信息
        Goods goods = goodsService.selectByPrimaryId(goodsId);
        if (null == goods) {
            return ResponseUtils.jsonFail("没有找到数据!");
        }
        Map<String, Object> goodsMap = Collections3.transBean2Map(goods);

        //五张图主图
        List<ImageItem> imageItemList = imageItemService.findImageItemList(goods.getGoodsImgPkgid(), ImageTypes.GOODS_COVERS_IMAGES);
        if (Collections3.isNotEmpty(imageItemList)) {
            for (ImageItem imageItem : imageItemList) {
                imageItem.setUri(systemFileService.getFileUrl() + "/" + imageItem.getUri());
            }
        }
        goodsMap.put("imageList", imageItemList);

        //服务标签
        List<ServerTags> serverTagList = serverTagService.findByGoodsId(goodsId);
        goodsMap.put("tags", serverTagList);

        //服务时间段
        List<GoodsServerTime> goodsServerTimeList = serverTimeService.findByGoodsId(goodsId);
        goodsMap.put("serverTimeList", goodsServerTimeList);

        //是否已经收藏
        boolean isCollection = false;
        if (null != user) {
            isCollection = collectionService.isCollection(user.getId(), goods.getGoodsId());
        }
        goodsMap.put("isCollection", isCollection);

        //TODO 顾客评价 于 评论数量 之间的关系

        //服务详情
        Article article = articleService.selectById(goods.getGoodsArticleId());
        goodsMap.put("detailContent", null == article ? "" : article.getContent());


        return ResponseUtils.jsonSuccess(goodsMap, "主信息查询成功!");
    }

    /**
     * 服务详情页-发布该服务得会员信息
     *
     * @param memberId 会员ID
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "detail/data/member", method = RequestMethod.GET)
    public ResponseMessage<?> detailDataMember(@RequestParam Long memberId) {
        Member member = memberService.findById(memberId);
        Map<String, Object> goodsMap = Collections3.transBean2Map(member);
        //头像
        //是否已关注
        //认证信息 用于下版本迭代
        //会员简介
        //会员表情
        return ResponseUtils.jsonSuccess(goodsMap, "主信息查询成功!");
    }


    /**
     * 服务详情页-评价 分页查询
     *
     * @param goodsId 服务ID
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "detail/data/moment", method = RequestMethod.GET)
    public ResponseMessage<?> detailDataMoment(@RequestParam Long goodsId) {
        return ResponseUtils.jsonSuccess(null);
    }


    /**
     * 加载服务详情页会员信息
     *
     * @param memberId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "detail/member/info", method = RequestMethod.GET)
    public ResponseMessage<?> detailAddCart(@RequestParam Long memberId) {
        Member member = memberService.findById(memberId);
        if (null == member) ResponseUtils.jsonFail("not found!");

        Map<String, Object> memberMap = Collections3.transBean2Map(member);
        memberMap.remove("password");
        //头像
        String image = "";
        if (null != member.getImagePkgId()) {
            List<ImageItem> imageItemList = imageItemService.findImageItemList(member.getImagePkgId(), ImageTypes.USER_ICON);
            image = Collections3.isNotEmpty(imageItemList) ? Collections3.getFirst(imageItemList).getUri() : "";
        }
        memberMap.put("image", systemFileService.getFileUrlByUri(image));
        //标签
        List<SpecificTag> specificTagList = Lists.newArrayList();
        List<MemberSpecificTag> memberSpecificTagList = memberSpecificTagService.findByMemberId(memberId);
        if (Collections3.isNotEmpty(memberSpecificTagList)) {
            List<Long> specificIdList = Collections3.extractToList(memberSpecificTagList, "specificId");
            specificTagList = specificTagService.findByIdList(specificIdList);
        }
        memberMap.put("specificTagList", specificTagList);
        //简介
        Article article = articleService.selectById(member.getArticleId());
        memberMap.put("remark", null == article ? "" : article.getContent());
        return ResponseUtils.jsonSuccess(memberMap);
    }


    /**
     * 全局搜索结果页面
     *
     * @return
     */
    @RequestMapping(value = "/search", method = RequestMethod.GET)
    public String search(@RequestParam String key) {
        //TODO 阿里云 open search 实现
        if ("天使投资".equals(key))
            return "demo/detail_01";
        else if ("VC投资".equals(key) || "风险投资".equals(key))
            return "demo/detail_02";
        else if ("PE投资".equals(key))
            return "demo/detail_03";
        else if ("麓谷政策".equals(key))
            return "demo/detail_04";
        else if ("证券开户".equals(key))
            return "demo/detail_06";
        else if ("美容".equals(key))
            return "demo/detail_05";
        else if ("投资".equals(key))
            return "demo/list";
        return "service/search";
    }


}